//
//  VisitingFamilyCell.m
//  CarLife
//
//  Created by yu on 2018/1/29.
//  Copyright © 2018年 jpas. All rights reserved.
//

#import "VisitingFamilyCell.h"

#import "QuestionModel.h"
#import "VisitingImageModel.h"
#import "WorkorderModel.h"
#import "VisitingInfoModel.h"
#import "Utility.h"
#import "User.h"
#import "NSString+JudgeString.h"
#import "UIImage+WaterMark.h"

@interface VisitingFamilyCell ()<
UITextViewDelegate,UITextFieldDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate
>

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, assign) NSInteger index;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageHeight;
@property (nonatomic, copy) NSString *loc;

@end

@implementation VisitingFamilyCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    _answerYTextView.delegate = self;
    _answerNTextView.delegate = self;

    _imageHeight.constant = 0;
    
    _visitorNameTF.delegate = self;
    _visitorMobileTF.delegate = self;
    
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
    [_imgView addGestureRecognizer:imageTap];
}

- (void)imageTap:(UITapGestureRecognizer *)tap
{
    if (_tapImageBlock) {
        _tapImageBlock(tap.view.tag-1);
    }
}

- (IBAction)photoAction:(UIButton *)btn {
    _index = btn.tag-1;
    if (_photoActionBlock) {
        _photoActionBlock(btn.tag-1,self.imagePicker);
    }
}

#pragma mark - ImagePicker Delegate -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSDictionary *imageMetadata = info[@"UIImagePickerControllerMediaMetadata"];
    NSDictionary *TIFFDictionary = [imageMetadata objectForKey:(NSString *)kCGImagePropertyTIFFDictionary];
    NSString *pictureTime = TIFFDictionary[@"DateTime"];

//    UIImage *waterImage = [Utility waterImage:image text:pictureTime font:35 frame:CGRectMake(20, 20, 1000, 100) location:[CLUser sharedUser].formattedAddress];
    
    CGFloat hRatio = image.size.height/250.0;
    CGFloat wRatio = image.size.width/(kScreenWidth-40);
    
    // TimeLabel
    UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280*wRatio, 15*hRatio)];
    timeLabel.text = pictureTime;
    timeLabel.textColor = [UIColor whiteColor];
    timeLabel.font = [UIFont systemFontOfSize:10*hRatio];
    timeLabel.backgroundColor = [UIColor clearColor];
    
    UIImage *timeImg = [self imageWithUIView:timeLabel];
    
    // LocationLabel
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280*wRatio, 25*hRatio)];
    //@"济南市军休大厦济南市军休大厦济南市军休大厦济南市军休大厦123";
    label.text = [User sharedUser].formattedAddress;
    label.numberOfLines = 0;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:10*hRatio];
    label.backgroundColor = [UIColor clearColor];
    
    UIImage *labelImg = [self imageWithUIView:label];
    
//    UIImage *resultImage = [image imageWaterMarkWithString:@"" rect:CGRectMake(0, 0, 0, 0 ) attribute:@{} image:labelImg imageRect:CGRectMake(0, 0, label.frame.size.width, label.frame.size.height) alpha:1];
    
    NSArray *rects = @[
  @[@(10),@(0),@(timeLabel.frame.size.width),@(timeLabel.frame.size.height)],
  @[@(10),@(timeLabel.frame.size.height),@(label.frame.size.width),@(label.frame.size.height)]];
    
    
    UIImage *resultImage = [image imageWaterMarkWithString:@"" rect:CGRectZero attribute:@{} images:@[timeImg,labelImg] imageRects:rects alpha:1];
    
    PPLog(@"%lf==%lf",labelImg.size.width,labelImg.size.height);
    
    // 把图片存model
    self.imageModel.image = resultImage;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_index inSection:3];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

//UIView转Image
- (UIImage *)imageWithUIView:(UIView*)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage *tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if (_pickerBlock) {
        _pickerBlock();
    }
}

///////////////////////家访人员信息/////////////////////
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _visitorNameTF) {
        if (textField.text.length) {
            [User sharedUser].visitorName = textField.text;
        }
    } else {
        if ([NSString valiMobile:textField.text]) {
            [User sharedUser].visitorMobile = textField.text;
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请输入正确手机号" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
}


////////////////////////调卷问查///////////////////////
- (void)textViewDidChange:(UITextView *)textView
{
    float textViewHeight = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)].height;
    CGRect frame = textView.frame;
    frame.size.height = textViewHeight + 5;
    textView.frame = frame;
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    //保存答案描述<1>
    if (textView == self.answerYTextView) {
        self.questionModel.answerDes = NSStringFormat(@"%@%@",self.questionModel.answerYdes,self.answerYTextView.text);//门牌号:12
        PPLog(@"textView%@",self.questionModel.answerDes);
    } else {
        self.questionModel.answerDes = NSStringFormat(@"%@%@",self.questionModel.answerNdes,self.answerNTextView.text);//原因:不详
        PPLog(@"textView%@",self.questionModel.answerDes);
    }
}

#pragma mark - YES
- (IBAction)answerYAction:(UIButton *)btn {

    self.questionModel.isAnswerYSelected = YES;
    self.questionModel.isAnswerNSelected = NO;

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.tag-1 inSection:2];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    //保存答案<2>
    self.questionModel.answer = @"1";
    
    self.questionModel.answerDes = NSStringFormat(@"%@",self.questionModel.answerYdes);
    self.answerNTextView.text = @"";
}

#pragma mark - NO
- (IBAction)answerNAction:(UIButton *)btn {
    
    self.questionModel.isAnswerYSelected = NO;
    self.questionModel.isAnswerNSelected = YES;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.tag-1 inSection:2];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
    //保存答案<2>
    self.questionModel.answer = @"0";
    
    self.questionModel.answerDes = NSStringFormat(@"%@",self.questionModel.answerNdes);
    self.answerYTextView.text = @"";
}

#pragma mark - WorkorderModel

- (void)setWoModel:(WorkorderModel *)woModel
{
    _woModel = woModel;
    
    self.nameLabel.text = NSStringFormat(@"姓名：%@",woModel.siteContact);
    self.owenerIdLabel.text = NSStringFormat(@"身份证号：%@",woModel.owenerId);
    self.mobileLabel.text = NSStringFormat(@"手机号：%@",woModel.siteContactTel);
    self.contractLabel.text = NSStringFormat(@"合同号：%@",woModel.contractNo);
    
    NSString *wordOrderType = woModel.wordOrderType;
    NSString *homeVisitType = woModel.homeVisitsType;
    if ([wordOrderType isEqualToString:@"4"]) {
        if ([homeVisitType isEqualToString:@"1"]) {//拜访家庭
            self.homeAddLabel.text = NSStringFormat(@"家庭地址：%@",woModel.installSite);
            self.companyAddLabel.text = @"";
            self.companyLabel.text = @"";
        } else {//拜访员工、私营业主
            self.homeAddLabel.text = @"";
            self.companyLabel.text = NSStringFormat(@"公司名称：%@",woModel.installer);
            self.companyAddLabel.text = NSStringFormat(@"公司地址：%@",woModel.installSite);
        }
    }
}

#pragma mark - VisitingInfoModel

- (void)setViModel:(VisitingInfoModel *)viModel
{
    _viModel = viModel;
    self.visitTimeLabel.text = NSStringFormat(@"上门日期：%@",viModel.visitTime);
    self.visitorNameTF.text = NSStringFormat(@"%@",viModel.visitorName);
    self.visitorMobileTF.text = NSStringFormat(@"%@",viModel.visitorMobile);
}


#pragma mark - QuestionModel

- (void)setQuestionModel:(QuestionModel *)questionModel
{
    _questionModel = questionModel;
    
    self.questionLabel.text = questionModel.question;
    self.answerYDesLabel.text = questionModel.answerYdes;
    self.answerNDesLabel.text = questionModel.answerNdes;
    
    self.answerYBtn.selected = questionModel.isAnswerYSelected;
    self.answerNBtn.selected = questionModel.isAnswerNSelected;
    
    NSArray *components = [questionModel.answerDes componentsSeparatedByString:@":"];
    NSString *des = components.lastObject;
    if (des.length) {
        self.answerYTextView.text = des;
        self.answerNTextView.text = des;
    }
    
    self.answerYDesLabel.hidden = !(questionModel.isAnswerYSelected && questionModel.answerYdes);
    self.answerNDesLabel.hidden = !(questionModel.isAnswerNSelected && questionModel.answerNdes);
    
    self.answerYTextView.hidden = !(questionModel.isAnswerYSelected && questionModel.answerYdes.length>0);
    self.answerNTextView.hidden = !(questionModel.isAnswerNSelected && questionModel.answerNdes.length>0);

}

#pragma mark - IMageModel

- (void)setImageModel:(VisitingImageModel *)imageModel
{
    _imageModel = imageModel;
    _photoDesLabel.text = imageModel.title;
    
    if (imageModel.image) {
        _imgView.image = imageModel.image;

        CGFloat width = imageModel.image.size.width;
        CGFloat height = imageModel.image.size.height;
        
        if (width > height) {
            _imageHeight.constant = 120;
        } else {
            _imageHeight.constant = 250;
        }
    }
}


+ (instancetype)initTableViewCellWith:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    NSString *identifier;
    NSInteger index = 0;
    switch (indexPath.section) {
        case 0:
            identifier = @"VisitingFamilyCell0";
            index = 0;
            break;
        case 1:
            identifier = @"VisitingFamilyCell1";
            index = 1;
            break;
        case 2:
            identifier = @"VisitingFamilyCell2";
            index = 2;
            break;
        case 3:
            identifier = @"VisitingFamilyCell3";
            index = 3;
            break;
        default:
            break;
    }
    
    VisitingFamilyCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"VisitingFamilyCell" owner:self options:nil] objectAtIndex:index];
    }
    return cell;
}

- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [UIImagePickerController new];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _imagePicker;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
